<!DOCTYPE HTML>
<html lang="en">
<head>
<title>RegExReplace() - Syntax &amp; Usage | AutoHotkey</title>
<meta name="description" content="The RegExReplace function replaces occurrences of a pattern (regular expression) inside a string." />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../static/theme.css" rel="stylesheet" type="text/css" />
<script src="../static/content.js" type="text/javascript"></script>
</head>
<body>

<h1>RegExReplace() <span class="ver">[v1.0.45+]</span></h1>

<p>Replaces occurrences of a pattern (regular expression) inside a string.</p>

<pre class="Syntax">NewStr := <span class="func">RegExReplace</span>(Haystack, NeedleRegEx <span class="optional">, Replacement := "", OutputVarCount := "", Limit := -1, StartingPosition := 1</span>)</pre>
<h2>Parameters</h2>
<dl>

  <dt>Haystack</dt>
  <dd><p>The string whose content is searched and replaced.</p></dd>

  <dt>NeedleRegEx</dt>
  <dd><p>The pattern to search for, which is a Perl-compatible regular expression (PCRE). The pattern's <a href="../misc/RegEx-QuickRef.htm#Options">options</a> (if any) must be included at the beginning of the string followed by a close-parenthesis. For example, the pattern &quot;<span class="red">i)</span>abc.*123&quot; would turn on the case-insensitive option and search for &quot;abc&quot;, followed by zero or more occurrences of any character, followed by &quot;123&quot;. If there are no options, the &quot;)&quot; is optional; for example, &quot;)abc&quot; is equivalent to &quot;abc&quot;.</p></dd>

  <dt>Replacement</dt>
  <dd><p id="BackRef">The string to be substituted for each match, which is plain text (not a regular expression). It may include backreferences like $1, which brings in the substring from <em>Haystack</em> that matched the first <a href="../misc/RegEx-QuickRef.htm#subpat">subpattern</a>. The simplest backreferences are $0 through $9, where $0 is the substring that matched the entire pattern, $1 is the substring that matched the first subpattern, $2 is the second, and so on. For backreferences above 9 (and optionally those below 9), enclose the number in braces; e.g. ${10}, ${11}, and so on. For <a href="RegExMatch.htm#NamedSubPat">named subpatterns</a>, enclose the name in braces; e.g. ${SubpatternName}. To specify a literal $, use $$ (this is the only character that needs such special treatment; backslashes are never needed to escape anything).</p>
      <p>To convert the case of a subpattern, follow the $ with one of the following characters: U or u (uppercase), L or l (lowercase), T or t (title case, in which the first letter of each word is capitalized but all others are made lowercase). For example, both $U1 and $U{1} transcribe an uppercase version of the first subpattern.</p>
      <p>Nonexistent backreferences and those that did not match anything in <em>Haystack</em> -- such as one of the subpatterns in &quot;(abc)|(xyz)&quot; -- are transcribed as empty strings.</p></dd>

  <dt>OutputVarCount</dt>
  <dd><p>Specify a variable in which to store the number of replacements that occurred (0 if none).</p></dd>

  <dt>Limit</dt>
  <dd><p>If <em>Limit</em> is omitted, it defaults to -1, which replaces <strong>all</strong> occurrences of the pattern found in <em>Haystack</em>. Otherwise, specify the maximum number of replacements to allow. The part of <em>Haystack</em> to the right of the last replacement is left unchanged.</p></dd>

  <dt>StartingPosition</dt>
  <dd><p>If <em>StartingPosition</em> is omitted, it defaults to 1 (the beginning of <em>Haystack</em>). Otherwise, specify 2 to start at the second character, 3 to start at the third, and so on.  If <em>StartingPosition</em> is beyond the length of <em>Haystack</em>, the search starts at the empty string that lies at the end of <em>Haystack</em> (which typically results in no replacements).</p>
      <p>If <em>StartingPosition</em> is less than 1, it is considered to be an offset from the end of <em>Haystack</em>. For example, 0 starts at the last character and -1 starts at the next-to-last character. If <em>StartingPosition</em> tries to go beyond the left end of <em>Haystack</em>, all of <em>Haystack</em> is searched.</p>
      <p>Regardless of the value of <em>StartingPosition</em>, the return value is always a complete copy of <em>Haystack</em> -- the only difference is that more of its left side might be unaltered compared to what would have happened with a <em>StartingPosition</em> of 1.</p></dd>

</dl>

<h2>Return Value</h2>
<p>This function returns a version of <em>Haystack</em> whose contents have been replaced by the operation. If no replacements are needed, <em>Haystack</em> is returned unaltered. If an error occurs (such as a syntax error inside <em>NeedleRegEx</em>), <em>Haystack</em> is returned unaltered (except in versions prior to 1.0.46.06, which return &quot;&quot;) and ErrorLevel is set to one of the values <a href="#ErrorLevel">below</a> instead of 0.</p>

<h2 id="ErrorLevel">Error Handling</h2>
<p><span class="ver">[v1.1.04+]</span>: This function is able to throw an exception on failure (not to be confused with &quot;no match found&quot;). For more information, see <a href="Catch.htm#RuntimeErrors">Runtime Errors</a>.</p>
<p><a href="../misc/ErrorLevel.htm">ErrorLevel</a> is set to one of the following:</p>
<ul>
  <li>0, which means that no error occurred.</li>
  <li>A string in the following form: <em>Compile error N at offset M: description</em>. In that string, <em>N</em> is the PCRE error number, <em>M</em> is the position of the offending character inside the regular expression, and <em>description</em> is the text describing the error.</li>
  <li>A negative number, which means an error occurred during the <em>execution</em> of the regular expression. Although such errors are rare, the ones most likely to occur are &quot;too many possible empty-string matches&quot; (-22), &quot;recursion too deep&quot; (-21), and &quot;reached match limit&quot; (-8). If these happen, try to redesign the pattern to be more restrictive, such as replacing each * with a ?, +, or a limit like {0,3} wherever feasible.</li>
</ul>
<h2>Options</h2>
<p>See <a href="../misc/RegEx-QuickRef.htm#Options">Options</a> for modifiers such as &quot;<span class="red">i)</span>abc&quot;, which turns off case-sensitivity in the pattern &quot;abc&quot;.</p>
<h2>Performance</h2>
<p>To replace simple substrings, use <a href="StringReplace.htm">StringReplace</a> because it is faster than RegExReplace().</p>
<p>If you know what the maximum number of replacements will be, specifying that for the <em>Limit</em> parameter improves performance because the search can be stopped early (this might also reduce the memory load on the system during the operation). For example, if you know there can be only one match near the beginning of a large string, specify a limit of 1.</p>
<p>To improve performance, the 100 most recently used regular expressions are kept cached in memory (in compiled form).</p>
<p>The <a href="../misc/RegEx-QuickRef.htm#Study">study option (S)</a> can sometimes improve the performance of a regular expression that is used many times (such as in a loop).</p>
<h2>Remarks</h2>
<p>Most characters like abc123 can be used literally inside a regular expression. However, the characters <strong>\.*?+[{|()^$</strong> must be preceded by a backslash to be seen as literal. For example, <strong>\.</strong> is a literal period and <strong>\\</strong> is a literal backslash. Escaping can be avoided by using \Q...\E. For example: <code>\QLiteral Text\E</code>.</p>
<p>Within a regular expression, special characters such as tab and newline can be escaped with either an accent (`) or a backslash (\). For example, `t is the same as \t.</p>
<p>To learn the basics of regular expressions (or refresh your memory of pattern syntax), see the <a href="../misc/RegEx-QuickRef.htm">RegEx Quick Reference</a>.</p>
<h2>Related</h2>
<p><a href="RegExMatch.htm">RegExMatch()</a>, <a href="../misc/RegEx-QuickRef.htm">RegEx Quick Reference</a>, <a href="../misc/RegExCallout.htm">Regular Expression Callouts</a>, <a href="StringReplace.htm">StringReplace</a>, <a href="InStr.htm">InStr()</a></p>
<p>Common sources of text data: <a href="FileRead.htm">FileRead</a>, <a href="URLDownloadToFile.htm">UrlDownloadToFile</a>, <a href="../misc/Clipboard.htm">Clipboard</a>, <a href="GuiControls.htm#Edit">GUI Edit controls</a></p>
<h2>Examples</h2>
<p>For general RegEx examples, see the <a href="../misc/RegEx-QuickRef.htm">RegEx Quick Reference</a>.</p>
<div class="ex" id="ExBasic">
<p><a href="#ExBasic">#1</a></p>
<pre>MsgBox % RegExReplace(&quot;abc123123&quot;, &quot;123$&quot;, &quot;xyz&quot;)  <em>; Shows &quot;abc123xyz&quot; because the $ allows a match only at the end.</em>
MsgBox % RegExReplace(&quot;abc123&quot;, &quot;i)^ABC&quot;)  <em>; Shows &quot;123&quot; because a match was achieved via the case-insensitive option.</em>
MsgBox % RegExReplace(&quot;abcXYZ123&quot;, &quot;abc<span class="red">(.*)</span>123&quot;, &quot;aaa<span class="red">$1</span>zzz&quot;)  <em>; Shows &quot;aaaXYZzzz&quot; by means of the <span class="red">$1</span> <a href="#BackRef">backreference</a>.</em>
MsgBox % RegExReplace(&quot;abc123abc456&quot;, &quot;abc\d+&quot;, &quot;&quot;, ReplacementCount)  <em>; Shows &quot;&quot; and stores 2 in ReplacementCount.</em></pre>
</div>

</body>
</html>
